﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Microsoft.Security.Application;
using MyLib;

namespace Billing2
{
    public partial class UploadAdjustmentReport : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.ucHighlight1.CloseAll();
            if (this.Session["SiteID"] == null)
            {
                base.Response.Redirect("default.aspx", true);
            }
            if (this.Page.IsPostBack)
                return;

            this.ViewState["SortDirection"] = "ASC";
            this.BindBillPeriod();
            this.BindOrganization();
            this.GetPermission();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ViewStateUserKey = Session.SessionID;
        }

        private void BindBillPeriod()
        {
            ClsBillPeriod cls1 = new ClsBillPeriod();
            this.ddlBillPeriod.DataSource = cls1.SelectGeneratedPeriod();
            this.ddlBillPeriod.DataTextField = "ServiceMonth";
            this.ddlBillPeriod.DataValueField = "ID";
            this.ddlBillPeriod.DataBind();
            DataTable dtCurrentPeriod = cls1.SelectCurrentPreiod();
            if ((dtCurrentPeriod.Rows != null) && (dtCurrentPeriod.Rows.Count > 0))
            {
                this.BillPeriodID = dtCurrentPeriod.Rows[0]["ID"].ToString();
            }
        }

        private void BindOrganization()
        {
            this.ddlOrganization.DataSource = new ClsOrganization().SelectAll();
            this.ddlOrganization.DataTextField = "OrgIDName";
            this.ddlOrganization.DataValueField = "ID";
            this.ddlOrganization.DataBind();
            this.BindSite();
        }

        public void BindSite()
        {
            this.ddlSite.Items.Clear();
            if (this.ddlOrganization.SelectedIndex == -1)
                return;
            this.ddlSite.DataSource = new ClsSitesInOrganization()
            {
                OrgID = Convert.ToInt64(this.ddlOrganization.SelectedValue)
            }.SelectByOrgID();
            this.ddlSite.DataTextField = "SiteIDName";
            this.ddlSite.DataValueField = "ID";
            this.ddlSite.DataBind();
            this.BindCostCentre();
        }

        private void BindCostCentre()
        {
            this.ddlCostCentre.Items.Clear();
            if (this.ddlSite.SelectedIndex == -1)
                return;
            this.ddlCostCentre.DataSource = new ClsCostCentresInSite()
            {
                SiteID = Convert.ToInt64(this.ddlSite.SelectedValue)
            }.SelectBySiteID();
            this.ddlCostCentre.DataTextField = "CostCentreIDName";
            this.ddlCostCentre.DataValueField = "ID";
            this.ddlCostCentre.DataBind();
        }

        protected void ddlOrganization_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlOrganization.SelectedIndex != -1)
            {
                this.BindSite();
            }
        }

        protected void ddlSite_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlSite.SelectedIndex != -1)
            {
                this.BindCostCentre();
            }
        }
   
        private void GetPermission()
        {
            ClsACLHelper cls = new ClsACLHelper();
            string pageName = this.Page.ToString().Substring(4, this.Page.ToString().Substring(4).Length - 5) + ".aspx";
            cls.SetPermission(LoginUser.TreeMenu, pageName);
            this.Update0 = cls.Update0;
            this.Read0 = cls.Read0;
            if (!cls.Read0)
            {
                base.Response.Redirect("logout.aspx",true);
            }
        }

        public string BillPeriodID
        {
            get
            {
                if (this.ddlBillPeriod.SelectedIndex == -1)
                {
                    return "0";
                }
                return this.ddlBillPeriod.SelectedValue;
            }
            set
            {
                this.ddlBillPeriod.SelectedIndex = -1;
                if ((value != "") && (value != "0"))
                {
                    this.ddlBillPeriod.SelectedIndex = this.ddlBillPeriod.Items.IndexOf(this.ddlBillPeriod.Items.FindByValue(value));
                }
            }
        }

        public string NewOrganizationID
        {
            get
            {
                if (this.ddlOrganization.SelectedIndex == -1)
                    return "0";
                else
                    return this.ddlOrganization.SelectedValue;
            }
            set
            {
                this.ddlOrganization.SelectedIndex = -1;
                if (value != "" && value != "0")
                    this.ddlOrganization.Items.FindByValue(value).Selected = true;
                this.BindSite();
            }
        }

        public string NewSiteID
        {
            get
            {
                if (this.ddlSite.SelectedIndex == -1)
                    return "0";
                else
                    return this.ddlSite.SelectedValue;
            }
            set
            {
                this.ddlSite.ClearSelection();
                if (value != "" && value != "0")
                    this.ddlSite.SelectedIndex = this.ddlSite.Items.IndexOf(this.ddlSite.Items.FindByValue(value));
                this.BindCostCentre();
            }
        }

        public string NewCostCentreID
        {
            get
            {
                if (this.ddlCostCentre.SelectedIndex == -1)
                    return "0";
                else
                    return this.ddlCostCentre.SelectedValue;
            }
            set
            {
                this.ddlCostCentre.SelectedIndex = -1;
                if (!(value != "") || !(value != "0"))
                    return;
                this.ddlCostCentre.SelectedIndex = this.ddlCostCentre.Items.IndexOf(this.ddlCostCentre.Items.FindByValue(value));
            }
        }

        public bool Read0
        {
            get
            {
                return Convert.ToBoolean(this.ViewState["xRead0"]);
            }
            set
            {
                this.ViewState["xRead0"] = value;
            }
        }

        public bool Update0
        {
            get
            {
                return Convert.ToBoolean(this.ViewState["xUpdate0"]);
            }
            set
            {
                this.ViewState["xUpdate0"] = value;
            }
        }

        protected void BtnRelease_Click(object sender, EventArgs e)
        {
            if (this.BillPeriodID == "0")
            {
                this.ucHighlight1.ErrorMessage = "Please select Site";
                return;
            }
            if (this.NewOrganizationID == "0")
            {
                this.ucHighlight1.ErrorMessage = "Please select Organization";
                return;
            }
            if (this.NewSiteID == "0")
            {
                this.ucHighlight1.ErrorMessage = "Please select Site";
                return;
            }
            if (this.NewCostCentreID == "0")
            {
                this.ucHighlight1.ErrorMessage = "Please select Cost Centre";
                return;
            }
            if (this.FileUpload1.PostedFile == null || this.FileUpload1.PostedFile.ContentLength == 0)
            {
                this.ucHighlight1.ErrorMessage = "Please select file to upload";
                return;
            }
            if (this.FileUpload1.PostedFile.ContentLength > 1024 * 1024)
            {
                this.ucHighlight1.ErrorMessage = "File size must less than 1MB!";
                return;
            }
            if (this.FileUpload2.PostedFile == null || this.FileUpload2.PostedFile.ContentLength == 0)
            {
                this.ucHighlight1.ErrorMessage = "Please select file to upload";
                return;
            }
            if (this.FileUpload2.PostedFile.ContentLength > 1024 * 1024)
            {
                this.ucHighlight1.ErrorMessage = "File size must less than 1MB!";
                return;
            }

            string fileName1 = System.IO.Path.GetFileName(this.FileUpload1.PostedFile.FileName);
            string fileExtension1 = System.IO.Path.GetExtension(fileName1).ToLower();
            if (fileExtension1 != ".pdf")
            {
                this.ucHighlight1.ErrorMessage = "Invalid file extension!";
                return;
            }
            string fileName2 = System.IO.Path.GetFileName(this.FileUpload2.PostedFile.FileName);
            string fileExtension2 = System.IO.Path.GetExtension(fileName2).ToLower();
            if (fileExtension2 != ".xls"
                && fileExtension2 != ".xlsx")
            {
                this.ucHighlight1.ErrorMessage = "Invalid file extension!";
                return;
            }

            try
            {
                string ccName = Common.db.SelectString("SELECT CostCentreIDName FROM CostCentresInSite WHERE ID = @ID", this.NewCostCentreID);
                int? NewVersion = Common.db.SelectInt(@"
                    SELECT ISNULL(MAX(version), 0) + 1
                    FROM BillReportRepository
                    WHERE BillReportTemplateID = @BillReportTemplateID
	                    AND BillPeriodID = @BillPeriodID
	                    AND SiteID = @SiteID
	                    AND CostCentreID = @CostCentreID
                    ", Common.AdjustmentReportTemplateID
                    , Convert.ToInt64(this.BillPeriodID)
                    , Convert.ToInt64(NewSiteID)
                    , Convert.ToInt64(NewCostCentreID));

                Common.db.Exec(@"
                UPDATE BillReportRepository
                SET IsLatest = 0
                WHERE BillReportTemplateID = @BillReportTemplateID
	                AND BillPeriodID = @BillPeriodID
	                AND SiteID = @SiteID
	                AND CostCentreID = @CostCentreID
                ", Common.AdjustmentReportTemplateID
                , Convert.ToInt64(this.BillPeriodID)
                , Convert.ToInt64(NewSiteID)
                , Convert.ToInt64(NewCostCentreID));

                long BillCustomerID = 0;
                ClsBillCustomer clsBillCust = new ClsBillCustomer();
                DataTable dtBillCust = clsBillCust.SelectByBillTypeSiteIDCostCentreID("", Convert.ToInt64(NewSiteID), Convert.ToInt64(NewCostCentreID));
                if ((dtBillCust != null) && (dtBillCust.Rows.Count > 0))
                {
                    BillCustomerID = Convert.ToInt64(dtBillCust.Rows[0]["ID"].ToString());
                }

                {
                    string reportName = Common.EscapeCostCenterName(ccName) + "_Adjustment_Report_V" + NewVersion.ToString() + fileExtension1;
                    Stream stream = this.FileUpload1.PostedFile.InputStream;
                    byte[] buffer = new byte[stream.Length];
                    int n = stream.Read(buffer, 0, buffer.Length);
                    if (n != buffer.Length)
                        throw new Exception("Invalid file");

                    ClsBillReportRepository clsRepository = new ClsBillReportRepository
                    {
                        BillPeriodID = Convert.ToInt64(this.BillPeriodID),
                        BillReportTemplateID = Common.AdjustmentReportTemplateID,
                        ReportFileName = reportName,
                        ReportData = buffer,
                        ContentType = "",
                        IsReleased = false,
                        SiteID = Convert.ToInt64(NewSiteID),
                        CostCentreID = Convert.ToInt64(NewCostCentreID),
                        CreatedBy = LoginUser.UserID,
                        DownloadID = ClsUtilityHelper.GenerateId(),
                        BillCustomerID = BillCustomerID,
                        Version = NewVersion.Value,
                        IsLatest = 1,
                        Thumbnail = ""
                    };
                    clsRepository.Save();
                }

                {
                    string reportName = Common.EscapeCostCenterName(ccName) + "_Adjustment_Report_V" + NewVersion.ToString() + fileExtension2;
                    Stream stream = this.FileUpload2.PostedFile.InputStream;
                    byte[] buffer = new byte[stream.Length];
                    int n = stream.Read(buffer, 0, buffer.Length);
                    if (n != buffer.Length)
                        throw new Exception("Invalid file");

                    ClsBillReportRepository clsRepository = new ClsBillReportRepository
                    {
                        BillPeriodID = Convert.ToInt64(this.BillPeriodID),
                        BillReportTemplateID = Common.AdjustmentReportTemplateID,
                        ReportFileName = reportName,
                        ReportData = buffer,
                        ContentType = "",
                        IsReleased = false,
                        SiteID = Convert.ToInt64(NewSiteID),
                        CostCentreID = Convert.ToInt64(NewCostCentreID),
                        CreatedBy = LoginUser.UserID,
                        DownloadID = ClsUtilityHelper.GenerateId(),
                        BillCustomerID = BillCustomerID,
                        Version = NewVersion.Value,
                        IsLatest = 1,
                        Thumbnail = ""
                    };
                    clsRepository.Save();
                }

                this.ucHighlight1.Message = "Upload adjustment report successfully!";
            }
            catch (Exception ex)
            {
                EPPLog.Logger.Error(ex.Message);
                this.ucHighlight1.ErrorMessage = "System error!";
                return;
            }

        }

    }
}